package gui;
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DragSource;
import org.eclipse.swt.dnd.DragSourceAdapter;
import org.eclipse.swt.dnd.DragSourceEvent;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.DropTargetAdapter;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;

public class DragDrop2Tables {
  public static void main(String[] args) {
    Display display = new Display();
    final Shell shell = new Shell(display);
    GridLayout grid = new GridLayout(3, false);
    shell.setLayout(grid);

    Button b1 = new Button(shell, SWT.NONE);
    b1.setText("add Colum");
    

    Button b2 = new Button(shell, SWT.NONE);
    b2.setText("Cereate Script");
    

    final Table table = new Table(shell, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
    
    final Transfer[] types = new Transfer[] { TextTransfer.getInstance() };
    DragSource source = new DragSource(table, DND.DROP_MOVE | DND.DROP_COPY);
    source.setTransfer(types);
    
    source.addDragListener(new DragSourceAdapter() {
      public void dragSetData(DragSourceEvent event) {
        // Get the selected items in the drag source
        DragSource ds = (DragSource) event.widget;
        Table table = (Table) ds.getControl();
        TableItem[] selection = table.getSelection();

        StringBuffer buff = new StringBuffer();
        for (int i = 0, n = selection.length; i < n; i++) {
          buff.append(selection[i].getText());
        }

         event.data = buff.toString();
      }
    });

   
    Listener createScriptListener = new Listener()
	{
		
		@Override
		public void handleEvent(Event paramEvent)
		{
			Object[] tables = shell.getChildren();
			int step=0;
			for(Object obj : tables){
//				System.out.println(obj.getClass());
				if(Group.class.isAssignableFrom( obj.getClass())){
					Group gr = (Group) obj;
					Object[] groupChildren = gr.getChildren();

					for(Object objChildren : groupChildren){
						if(Table.class.isAssignableFrom( objChildren.getClass())){
//							System.out.println("Table");
							Table t = (Table) objChildren;
							TableItem[] items = t.getItems();				
							step++;
							for(TableItem ti : items){
								System.out.println("step:"+  step +" item:"+ti.getText());
							}
						}
						
					}
				}
				
			}			
		}
	};
    
    Listener addColumnListener = new Listener()
	{
		@Override
		public void handleEvent(Event arg0)
		{
			GridLayout p = (GridLayout) shell.getLayout();
			int gridCols= p.numColumns+1;
			GridLayout gridN =  new GridLayout(gridCols, false);
			shell.setLayout(gridN);
			final int step =gridCols-3;
			System.out.println(gridCols);
			
			
			Group g = new Group(shell, SWT.NONE);
			GridLayout gridGroup =  new GridLayout(1, false);
			g.setLayout(gridGroup);
			g.setText("Step: "+step);
			
			Button delete = new Button(g, SWT.NONE);
			delete.setText("Delete This Step");
			    

		    Button clear = new Button(g, SWT.NONE);
		    clear.setText("Clear This Step");
		    
		  

		    final Table newTable = new Table(g, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
		    newTable.setBackground(new Color(Display.getCurrent (), 128,255,128));
		    // Create the drop target
		    DropTarget target3 = new DropTarget(newTable, DND.DROP_MOVE | DND.DROP_COPY | DND.DROP_DEFAULT);
		    target3.setTransfer(types);
		    target3.addDropListener(new DropTargetAdapter() {
		      public void dragEnter(DropTargetEvent event) {
		        if (event.detail == DND.DROP_DEFAULT) {
		          event.detail = (event.operations & DND.DROP_COPY) != 0 ? DND.DROP_COPY : DND.DROP_NONE;
		        }

		        // Allow dropping text only
		        for (int i = 0, n = event.dataTypes.length; i < n; i++) {
		          if (TextTransfer.getInstance().isSupportedType(event.dataTypes[i])) {
		            event.currentDataType = event.dataTypes[i];
		          }
		        }
		      }

		      public void dragOver(DropTargetEvent event) {
		         event.feedback = DND.FEEDBACK_SELECT | DND.FEEDBACK_SCROLL;
		      }
		      public void drop(DropTargetEvent event) {
		        if (TextTransfer.getInstance().isSupportedType(event.currentDataType)) {
		          // Get the dropped data
		          DropTarget target = (DropTarget) event.widget;
		          Table table = (Table) target.getControl();
		          String data = (String) event.data;
		          data = data.replace("_", "");
		          // Create a new item in the table to hold the dropped data
		          TableItem item = new TableItem(table, SWT.NONE);
		          item.setText(new String[] { data });
		          table.redraw();
		          shell.layout();
		        }
		      }
		    });
		    
		    Listener deleteStep = new Listener()
			{
				
				@Override
				public void handleEvent(Event paramEvent)
				{
					Object[] children = shell.getChildren();
					boolean deleted=false;
					int newStep=0;
					for(Object obj : children){
						if(Group.class.isAssignableFrom( obj.getClass())){
							Group gr = (Group) obj;
							if (gr.getText().equalsIgnoreCase("Step: "+step)){
								gr.dispose();
								deleted = true;
								newStep=step;
								continue;
							}
							if(deleted){
								gr.setText("Step: "+newStep);
								newStep++;
							}
							
						}
					}
				
					GridLayout p = (GridLayout) shell.getLayout();
					int gridCols= p.numColumns-1;
					GridLayout gridN =  new GridLayout(gridCols, false);
					shell.setLayout(gridN);					
					shell.layout();
				}
			};
		    
		    
		    Listener clearStep = new Listener()
			{

				@Override
				public void handleEvent(Event paramEvent)
				{
					newTable.setItemCount(0);
					shell.layout();
				}
				
			};			
			clear.addListener(SWT.Selection, clearStep);
			delete.addListener(SWT.Selection, deleteStep);
			
			shell.layout();
		
		}
		
		
	}; 
	

	b1.addListener(SWT.Selection, addColumnListener);
	b2.addListener(SWT.Selection, createScriptListener);
    
    TableColumn column = new TableColumn(table, SWT.NONE);

    // Seed the table
    TableItem item = new TableItem(table, SWT.NONE);
    item.setText(new String[] { "_A" });
    item = new TableItem(table, SWT.NONE);
    item.setText(new String[] { "_B" });
    item = new TableItem(table, SWT.BORDER);
    item.setText(new String[] { "_C" });

    column.pack();
    shell.open();

    while (!shell.isDisposed()) {
      if (!display.readAndDispatch()) {
        display.sleep();
      }
    }
    display.dispose();
  }
}
